package com.gutai.admin.service.impl;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;

import com.gutai.admin.dao.IProductDao;
import com.gutai.admin.entity.Goods;
import com.gutai.admin.entity.Product;
import com.gutai.admin.service.IGoodsService;
import com.gutai.admin.service.IProductService;

/**
 * 
 * 描述：
 * 
 * <pre>
 * HISTORY
 * ****************************************************************************
 *  ID    DATE            PERSON            REASON
 *  1     2018年11月7日         YC           Create
 * ****************************************************************************
 * </pre>
 * 
 * @author YC
 * @version 1.0
 */
@Service
@CacheConfig(cacheNames = "product")
public class ProductService implements IProductService {

    @Autowired
    private IProductDao productDao;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IProductService productService; // 注入自己，内部调用使用缓存
    
    @Override
    public List<Product> getList(String goodsName) {
//        return productDao.findByGoodsId(goodsId);
        List<Integer> goodsIds = goodsService.findByName(goodsName).stream().map(Goods::getId).collect(Collectors.toList());
        return productService.getAll().stream()
                .filter(item -> goodsIds.contains(item.getGoodsId())).collect(Collectors.toList());
    }

    @Override
    @Cacheable(unless = "#result == null || #result.size()==0")
    public List<Product> getAll() {
        Sort sort = new Sort(Direction.DESC, "createTime");
        return productDao.findAll(sort);
    }

    
    @Override
    @CacheEvict(allEntries = true)
    public void add(Product entity) {
        entity.setGoodsSn(String.valueOf(entity.getGoodsId()));
        productDao.save(entity);
    }

    @Override
    @CacheEvict(allEntries = true)
    public void update(Product entity) {
        productDao.saveAndFlush(entity);
    }

    @Override
    @CacheEvict(allEntries = true)
    public void delete(int id) {
        productDao.deleteById(id);
    }

    @Override
    public Product findById(int id) {
        return productDao.findById(id);
    }
}
